import React, { Component, PropTypes } from 'react';
import { Utility, GxIcon, GxSearchBar, Tabs, ApiInfo, Refresh } from 'components';
import { connect } from 'react-redux';
import * as CommonActions from 'redux/modules/reduxCommon';
const styles = require('./scss/GmessageDealt.scss');

@connect(
  state => ({
    Title: state.Common.Title,                                          // 标题
    UrlParams: state.Common.UrlParams,                                  // URL参数
    GxMessageDealt: state.Common.GxMessageDealt,                        // URL参数
  }),
  { ...CommonActions })

export default class GmessageDealt extends Component {
  static propTypes = {
    Title: PropTypes.string,                                            // 标题
    UrlParams: PropTypes.object,                                        // url 参数
    GxMessageDealt: PropTypes.object,                                   // 
    onDeleteByFields: PropTypes.func,                                   // 
    onSetContent: PropTypes.func,                                       // 
    onUpdateRedux: PropTypes.func,                                      // 
    onApiGet: PropTypes.func,                                           // 
    onApiPost: PropTypes.func,                                          // 
    onApiPut: PropTypes.func,                                           // 
  };

  constructor(props) {
    super(props);
    this.state = { RefreshComplete: true, NextDataComplete: true, TIndex: 0, TempIndex: 0 };
    this.state.TabList = [
      { Title: '速记', Status: 0, onSelect: this.__HandlerSwitchTab.bind(this) },
      { Title: '存档', Status: 1, onSelect: this.__HandlerSwitchTab.bind(this) },
    ];
  }

  componentDidMount() {
    this.state.IsMount = true;
    const { GxMessageDealt } = this.props;
    const { List } = GxMessageDealt || {};
    if (!Utility.isArray(List)) {
      this.__InitData({});
    }
    const { btnFocus } = this.refs;
    if (btnFocus) {
      btnFocus.focus();
    }
  }

  componentWillUnmount() {
    delete this.state.IsMount;
  }

  /**
   * 更新渲染
   */
  __UpdateRender() {
    if (!!this.state.IsMount) {
      this.setState({ __CurrentTempDate: new Date().getTime() });
    }
  }

  __InitData(condition) {
    const keyword = this.state.KeyWord;
    const params = Object.assign({}, { keyword, page: 0, size: 15, __ContentArray: true }, condition || {});
    const { onApiGet } = this.props;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }

    const __Complete = () => {
      delete this.state.IsBusying;
      this.state.NextDataComplete = true;
      this.state.RefreshComplete = true;
      this.__UpdateRender();
    };
    const __self = this;
    const { TIndex } = this.state;
    onApiGet('GxMessageDealt', TIndex === 1 ? ApiInfo.JXDB.BackupList : ApiInfo.JXDB.ToDoList, { params: params }).then(() => {
      __self.__InitDataByResult();
      __Complete();
    }, () => {
      __Complete();
    });
  }

  __InitDataByResult() {
    const { GxMessageDealt } = this.props;
    const { Condition } = GxMessageDealt || {};
    const { IsExistsNextData } = Condition || {};
    this.state.IsNextData = IsExistsNextData;
  }

  __HandlerSwitchTab(item, index) {
    this.state.TIndex = index;
    this.state.RefreshComplete = false;
    this.__UpdateRender();
    this.__InitData({}, false);
  }

  /**
 * 搜索事件
 * 
 * @param {any} key 
 * @returns 
 * @memberof GmessageDealt
 */
  __HandlerSearch(key) {
    this.state.__TempKeyWork = key;
    if (!!this.state.isLockSearch) {
      return;
    }
    this.state.isLockSearch = true;
    this.state.QTime = new Date().getTime();

    const _inter = setInterval(() => {
      const __CTime = new Date().getTime();
      const _OTime = this.state.QTime;
      this.state.TempIndex++;
      console.log('index -->:', this.state.TempIndex, '--> key:', this.state.__TempKeyWork);
      if (this.state.KeyWord === this.state.__TempKeyWork) {
        this.state.TempIndex = 0;
        console.log('KeyWord === key--index -->:', this.state.TempIndex);
        clearInterval(_inter);
        this.state.isLockSearch = false;
      }

      if (__CTime - _OTime > 1000) {
        if (!!this.state.IsBusying) {
          console.log('正在调用接口请等待....');
          return;
        }
        this.state.IsBusying = true;

        clearInterval(_inter);
        this.state.KeyWord = this.state.__TempKeyWork;
        delete this.state.__TempKeyWork;
        this.state.isLockSearch = false;
        console.log('开始调用接口了index -->:%d,KeyWord:%s', this.state.TempIndex, this.state.KeyWord);
        this.__InitData({}, false);
      }
    }, 200);
  }

  __HandlerOnKeep() {
    const { onApiPut, onUpdateRedux, onSetContent } = this.props;
    if (!Utility.isFunction(onApiPut)) {
      return;
    }

    const self = this;
    const __Submit = () => {
      Utility.$loading();
      onApiPut('GMessageDetailInfo', ApiInfo.JXDB.ToBackup, {}).then(() => {
        onSetContent('GxMessageDealt', null);
        onUpdateRedux();
        self.__UpdateRender();
        Utility.$actionSheet('存档成功');
        Utility.$loadingHide();
      }, () => {
        Utility.$loadingHide();
      });
    };
    Utility.$showDialogConfirm('您真的存档吗？', null, () => {
      __Submit();
    });
  }

  __HandlerNextData() {
    const { GxMessageDealt } = this.props;
    const { Condition } = GxMessageDealt || {};
    const { IsExistsNextData } = Condition || {};
    if (!IsExistsNextData) {
      return;
    }
    this.state.NextDataComplete = false;
    this.__UpdateRender();
    this.__InitData(Condition, true);
  }

  __HandlerRefresh() {
    this.state.RefreshComplete = false;
    this.__UpdateRender();
    this.__InitData({}, false);
  }

  __HandlerToGXin(item, isFinish) {
    const { onApiPost, onSetContent, onUpdateRedux, onDeleteByFields } = this.props;
    const { id } = item;
    if (!isFinish) {
      const { SelectEndDate, SelectExecutePlanType, SelectLabelType, SelectRemindType, SelectRepeatWay, SelectWorkWay } = Utility.constItem.StateName;
      onSetContent('DealtDetailTemp', null);
      onSetContent(SelectExecutePlanType, null);
      onSetContent(SelectLabelType, null);
      onSetContent(SelectRemindType, null);
      onSetContent(SelectRepeatWay, null);
      onSetContent(SelectWorkWay, null);
      onSetContent(SelectEndDate, null);
      onSetContent('DealtDetailTemp', null);

      onSetContent(Utility.constItem.StateName.DealtDetail, item);
      Utility.toPage(Utility.constItem.UrlItem.ToGMessage, { id });
      return;
    }
    if (!Utility.isFunction(onApiPost)) {
      return;
    }

    const _api = Utility.format(!!isFinish ? ApiInfo.JXDB.ToGxinFinish : ApiInfo.JXDB.ToGxin, id);
    Utility.$loading();
    const __Complete = () => {
      onUpdateRedux();
      delete this.state.SelectId;
      this.__UpdateRender();
      Utility.$loadingHide();
    };
    onApiPost('ToGXinInfo', _api, {}).then(() => {
      onDeleteByFields('GxMessageDealt', { Key: 'id', Value: id });
      __Complete();
    }, () => {
      __Complete();
    });
  }

  __HandlerProcessData() {
    const { GxMessageDealt } = this.props;
    const { List } = GxMessageDealt || {};
    if (!Utility.isArray(List)) {
      return [];
    }
    const __ResultInfo = {};
    const __Week = { '0': '日', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六' };
    List.forEach((item) => {
      const { createTime } = item;
      const _Time = new Date(createTime);
      const _Month = _Time.getFullYear() + '年' + (_Time.getMonth() + 1) + '月';
      if (!__ResultInfo[_Month]) {
        __ResultInfo[_Month] = { Month: _Month, days: [] };
      }
      const days = __ResultInfo[_Month].days;
      let dayInfo = __ResultInfo[_Month].dayInfo;
      const week = '周' + __Week[_Time.getDay()];
      const day = _Time.getDate();
      const dw = day + '_' + week;
      if (!dayInfo || !dayInfo[dw]) {
        item.week = week;
        item.day = day;
        dayInfo = {};
        dayInfo[dw] = dw;
        __ResultInfo[_Month].dayInfo = dayInfo;
      }
      days.push(item);
    });

    const data = Object.values(__ResultInfo);
    return data;
  }

  __BuildHTML() {
    const { SelectId, TIndex } = this.state;
    // const { onSetContent } = this.props;
    const DataList = this.__HandlerProcessData();
    return DataList.map((row, index) => {
      const { Month, days } = row;
      return (
        <div key={index} className={styles.row} >
          <div className={styles.yearAndMonth}>{Month}</div>
          {
            days.map((obj, sIndex) => {
              const { id, day, week, content, execerList } = obj;
              let _pi = execerList;
              const pList = execerList.split(',');
              if (pList.length > 3) {
                _pi = pList.slice(0, 3).join(',') + '等' + pList.length + '人';
              }
              return (
                <div className={styles.bom + ' ' + (sIndex === (days.length - 1) ? styles.bomLast : '')} key={sIndex}>
                  <div className={styles.bData}>
                    <div className={styles.left}>
                      <div className={styles.space}></div>
                      <div className={styles.day}>{day}</div>
                      <div className={styles.week}>{week}</div>
                    </div>
                    <div className={styles.center}>
                      <div className={styles.c1 + ' ' + (sIndex === 0 ? styles.disabled : '')}></div>
                      <div className={styles.c2}><div></div></div>
                      <div className={styles.c3 + ' ' + (sIndex === (days.length - 1) ? styles.disabled : '')}></div>
                    </div>
                    <div className={styles.splitLine}>
                      <div className={styles.line}></div>
                    </div>
                    <div className={styles.right}>
                      <div className={styles.data}>
                        <div className={styles.top} onClick={() => {
                          if (TIndex === 1) {
                            return;
                          }
                          this.__HandlerToGXin(obj, false);
                          //   onSetContent(Utility.constItem.StateName.DealtDetail, obj);
                          //   Utility.toPage(Utility.constItem.UrlItem.DealtEdit, { id: obj.id });
                        }}>{content}</div>
                        {
                          TIndex === 0 &&
                          <div className={styles.bottom}>
                            <div className={styles.icon}>
                              <GxIcon IconType="iconRecipient" IsHidePadding />
                            </div>
                            <div className={styles.peopleList}>{_pi}</div>
                            <div className={styles.more}>
                              <GxIcon IconType="iconMore" IsHidePadding onClick={() => {
                                this.state.SelectId = id;
                                this.__UpdateRender();
                              }} />
                            </div>
                          </div>
                        }
                      </div>
                    </div>
                  </div>
                  {
                    SelectId === id &&
                    <div className={styles.operator + ' ' + (SelectId === id ? styles.show : '')}>
                      <div className={styles.bg} onClick={() => {
                        delete this.state.SelectId;
                        this.__UpdateRender();
                      }}></div>
                      <div className={styles.gc + ' ' + styles.tooltip}>
                        <div onClick={this.__HandlerToGXin.bind(this, obj, false)} className={styles.gx}>转G信</div>
                        <div onClick={this.__HandlerToGXin.bind(this, obj, true)} className={styles.complete}>完成</div>
                      </div>
                    </div>
                  }
                </div>
              );
            })
          }
        </div>
      );
    });
  }

  render() {
    const { TabList, TIndex, RefreshComplete, NextDataComplete, IsNextData } = this.state;
    const { GxMessageDealt } = this.props;
    const { List } = GxMessageDealt || {};

    return (
      <div className={styles.messageDealtCss}>
        <div className={styles.search}>
          <GxSearchBar Title="搜索" IsHideCancel
            onSearch={this.__HandlerSearch.bind(this)}
          />
        </div>
        <Tabs Items={TabList} SelectIndex={TIndex || 0} />
        <Refresh Percentage={20} RefreshComplete={RefreshComplete} NextDataComplete={NextDataComplete}
          onRefresh={this.__HandlerRefresh.bind(this)} onNextData={this.__HandlerNextData.bind(this)}>
          <div className={styles.list}>
            {
              this.__BuildHTML()
            }
          </div>
        </Refresh>
        <div className={styles.last}>
          {
            IsNextData === false &&
            <span> 别扯了,我是有底线的。</span>
          }
        </div>
        {
          (TIndex === 0 || TIndex === '0') && Utility.isArray(List) &&
          <div className={styles.btnKeep}>
            <div onClick={this.__HandlerOnKeep.bind(this)}>一键存档</div>
          </div>
        }
        <button className={styles.btnFocus} ref="btnFocus">a</button>
      </div>
    );
  }
}
